//
//  MySelfViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/27.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "MySelfViewController.h"
#import "MyselfView.h"
#import "MySelfTableViewCell.h"
#import "MyAccountViewController.h"
#import "PushOutViewController.h"
#import "MyEarningsViewController.h"
#import "CallToServiceViewController.h"
#import "NewsViewController.h"
#import "SettingsViewController.h"
#import "AppDelegate.h"
#import "BlackNavViewController.h"
#import "LoginViewController.h"
#import "SystemMessageViewController.h"
#import "AboutDCMViewController.h"
#import "HistoryOrderViewController.h"


@interface MySelfViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak)UIImageView * backImage;

@property (nonatomic, strong)MyselfView * myView;

@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)NSArray * imageNameArray;

@property (nonatomic, strong)NSArray * showStringArray;

//@property (nonatomic, copy)NSString * nameString;
@property (nonatomic, strong)NSTimer * countDownTimer;

@end

@implementation MySelfViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 2;


- (void)viewWillAppear:(BOOL)animated{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * userID = [userDefaults objectForKey:@"userId"];
    
    if (userID) {
    
        [self loadData];
    }

}

- (void)loadData{
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    
//    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString * userID = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"userId"]];
//    NSString * lastLoginTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"lastLoginTime"]];
//    NSString * createTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"createTime"]];
//    
//    [NetworkTool sharedTools].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
//    
//    [NetworkTool sharedTools].requestSerializer = [AFHTTPRequestSerializer serializer];
//
//    [[NetworkTool sharedTools].requestSerializer setValue:createTimeStr forHTTPHeaderField:@"createTime"];
//    [[NetworkTool sharedTools].requestSerializer setValue:lastLoginTimeStr forHTTPHeaderField:@"lastLoginTime"];
//    [[NetworkTool sharedTools].requestSerializer setValue:userID forHTTPHeaderField:@"userId"];
//    
//    [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//        
//        NSDictionary * dict = responseObject[@"param"];
//        
//        NSDictionary * otherInfoDict = dict[@"otherInfo"];
////        NSDictionary * financeDict = dict[@"finance"];
//        
//        NSString * urlString = otherInfoDict[@"avatar"];
//        
//        if ([urlString isEqualToString:@""]) {
//            self.myView.userIconImageView.image = [UIImage imageNamed:@"默认头像"];
//        }else{
//            self.myView.iconImageString = urlString;
//        }
//        
//        
//        
//        NSString * nikeName = [NSString stringWithFormat:@"%@", otherInfoDict[@"nickname"]];
//        
//        if ([nikeName isEqualToString:@""]) {
//            
//            self.nameString = [NSString stringWithFormat:@"%@", otherInfoDict[@"phone"]];
//            self.myView.nameString = [NSString stringWithFormat:@"%@", otherInfoDict[@"phone"]];//otherInfoDict[@"nickname"];emailtring
//        }else{
//           
//            self.nameString = nikeName;
//            self.myView.nameString = nikeName;//otherInfoDict[@"nickname"];emailtring
//        }
//        
//        
//        self.myView.emailtring = [NSString stringWithFormat:@"%@", otherInfoDict[@"email"]];
//        
//        NSString * totalAssets = [NSString stringWithFormat:@"%@", dict[@"balance"]];
//        float total = [totalAssets floatValue];
//        
//        if (total == 0) {
//             self.myView.allMoneyString = @"$0.00";
//        }else{
//            self.myView.allMoneyString = [NSString stringWithFormat:@"$%.2f",total];//financeDict[@"totalAssets"];
//        }
//        
////        NSString * cashAvailableString = [NSString stringWithFormat:@"%@", dict[@"cashAvailable"]];
//        float floatProfit = [dict[@"floatProfit"] floatValue];
//        float marginFree = [dict[@"marginFree"] floatValue];
//        
//        float canUseMoney = total + floatProfit - marginFree;
//        
////        float cashAvailable = [cashAvailableString floatValue];
//       
//        self.myView.userMoneyString = [NSString stringWithFormat:@"$%.2f", canUseMoney];//dict[@"cashAvailable"];
//        
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//    
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        NSLog(@"%@",error);
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        
//        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                       message:@"网络连接失败！"
//                                                                preferredStyle:UIAlertControllerStyleAlert];
//        
//        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                              handler:^(UIAlertAction * action) {
//                                                                  //响应事件
//                                                                  
//                                                              }];
//        
//        [alert addAction:defaultAction];
//        [self presentViewController:alert animated:YES completion:nil];
//    }];
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    /*
     [userDefaults setObject:balanceFloatString forKey:@"balance"];
     [userDefaults setObject:floatProfitString forKey:@"floatProfit"];
     [userDefaults setObject:clearMoneyString forKey:@"clearMoney"];
     [userDefaults setObject:canUseMoneyString forKey:@"canUseMoney"];
     [userDefaults setObject:nickName forKey:@"nickName"];
     [userDefaults setObject:iconUrl forKey:@"iconUrl"];
     [userDefaults setObject:emailString forKey:@"emailString"];
     */
    
    NSString * balance = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"balance"]];
    NSString * canUseMoney = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"canUseMoney"]];
    NSString * iconUrl = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"iconUrl"]];
    NSString * nickName = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"nickNameString"]];
    NSString * emailString = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"emailString"]];
    
    self.myView.allMoneyString = balance;
    self.myView.userMoneyString = canUseMoney;
    self.myView.iconImageString = iconUrl;
    self.myView.nameString = nickName;
    self.myView.emailtring = emailString;
    
    [self setupDownTimer];
}


- (void)setupDownTimer{
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown == 0){
        
        [_countDownTimer invalidate];
        
        [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSDictionary * dict = responseObject[@"param"];
            
            float allMoneyString = [dict[@"balance"] floatValue];
            float userMoneyString = [dict[@"marginFree"] floatValue];
            
            self.myView.allMoneyString = [NSString stringWithFormat:@"$%.2f",allMoneyString];
            self.myView.userMoneyString = [NSString stringWithFormat:@"%.2f",userMoneyString];
            
            secondsCountDown = 2;
            
            [self setupDownTimer];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];
        
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString * userID = [userDefaults objectForKey:@"userId"];
//    
//    if (userID) {
//        
//        [self loadData];
//    }
    
//    _showStringArray = @[@"账户",@"推广赚钱",@"我的收益",@"联系客服",@"新闻资讯",@"关于DCM",@"系统设置"];
//    _imageNameArray = @[@"账户",@"推广赚钱",@"我的收益",@"联系客服",@"新闻资讯",@"d",@"设置资料"];
    
    _showStringArray = @[@"历史订单",@"账户",@"联系客服",@"新闻资讯",@"关于DCM",@"系统设置"];
    _imageNameArray = @[@"我的－历史订单",@"账户",@"联系客服",@"新闻资讯",@"d",@"设置资料"];
    
    [self setupNavBar];
    [self setupUI];
//    [self setupTableView];
}


- (void)setupNavBar{
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0 * SCREENH6, 0 * SCREENH6, 22 * SCREENH6, 25 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];

    [backButton addTarget:self action:@selector(pushToSystemMessage) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.rightBarButtonItem = leftButton;
}



- (void)setupUI{
    
    UIImageView * backImage = [[UIImageView alloc] initWithFrame:self.view.bounds];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    backImage.userInteractionEnabled = YES;
    
    self.backImage = backImage;
    
    [self.view addSubview:self.backImage];
    
    self.myView = [[MyselfView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 143 * SCREENH6)];

    self.myView.nameString = @"---";
    self.myView.emailtring = @"---";
    self.myView.userIconImageView.image = [UIImage imageNamed:@"默认头像"];
    self.myView.userMoneyString = @"$0.00";
    self.myView.allMoneyString = @"$0.00";
    
    [self.backImage addSubview:self.myView];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 207 * SCREENH6, SCREEN_WIDTH, SCREENH_HEIGHT - 143 * SCREENH6)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"背景"]];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[MySelfTableViewCell class] forCellReuseIdentifier:@"myselfCell"];
    
    [self.backImage addSubview:self.tableView];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MySelfTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myselfCell" forIndexPath:indexPath];
    
    cell.explationLabel.text = self.showStringArray[indexPath.row];
    cell.iconImage.image = [UIImage imageNamed:self.imageNameArray[indexPath.row]];

    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        return 65 * SCREENH6;
        
    }else{
        
        return 58 * SCREENH6;
    }
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * userID = [userDefaults objectForKey:@"userId"];
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
    
    
    
    if (indexPath.row == 0) {
        
        HistoryOrderViewController * historyVC = [HistoryOrderViewController new];
        
        [self.navigationController pushViewController:historyVC animated:YES];
        
        
    }else if (indexPath.row == 1){
        
        if (userID) {
            
            MyAccountViewController * myAccount = [MyAccountViewController new];
            
            [self.navigationController pushViewController:myAccount animated:YES];
        }else{
            
            appDelegate.window.rootViewController = navVC;
        }
        
//        if (userID) {
//            
////            PushOutViewController * pushVC = [PushOutViewController new];
////            
////            [self.navigationController pushViewController:pushVC animated:YES];
//            
//            [self showAlertView];
//            
//        }else{
//            
//            appDelegate.window.rootViewController = navVC;
//        }
        
    }else if (indexPath.row == 2){
        
//        if (userID) {
//            
////            MyEarningsViewController * myRaenVC = [MyEarningsViewController new];
////            
////            [self.navigationController pushViewController:myRaenVC animated:YES];
//            [self showAlertView];
//            
//        }else{
//            
//            appDelegate.window.rootViewController = navVC;
//        }
        CallToServiceViewController * callServiceVC = [CallToServiceViewController new];
        
        [self.navigationController pushViewController:callServiceVC animated:YES];

    }else if (indexPath.row == 3){
        
//        CallToServiceViewController * callServiceVC = [CallToServiceViewController new];
//        
//        [self.navigationController pushViewController:callServiceVC animated:YES];
        
        NewsViewController * newsVC = [NewsViewController new];
        
        [self.navigationController pushViewController:newsVC animated:YES];

    }
    else if (indexPath.row == 4){
        
//        NewsViewController * newsVC = [NewsViewController new];
//        
//        [self.navigationController pushViewController:newsVC animated:YES];
        AboutDCMViewController * aboutVC = [AboutDCMViewController new];
        
        [self.navigationController pushViewController:aboutVC animated:YES];

    }
//    else if (indexPath.row == 5){
//        
//        AboutDCMViewController * aboutVC = [AboutDCMViewController new];
//        
//        [self.navigationController pushViewController:aboutVC animated:YES];
//        
//    }
    else{
        
        if (userID) {
            
            SettingsViewController * settingVC = [SettingsViewController new];
            
            settingVC.nameString = self.myView.nameString;
            settingVC.iconImage = self.myView.userIconImageView.image;
            
            [self.navigationController pushViewController:settingVC animated:YES];
            
            [settingVC returnIconImage:^(UIImage *iconImage) {
                
                self.myView.userIconImageView.image = iconImage;
            }];
            
        }else{
            
            appDelegate.window.rootViewController = navVC;
        }
        
        
    }
    
    
    
    self.hidesBottomBarWhenPushed = NO;
}


//跳转到系统消息
- (void)pushToSystemMessage{
    
    self.hidesBottomBarWhenPushed = YES;
    
    SystemMessageViewController * messageVC = [SystemMessageViewController new];
    
    [self.navigationController pushViewController:messageVC animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}



- (void)showAlertView{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"敬请期待！"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              //响应事件
//                                                              NSLog(@"action = %@", action);
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [_countDownTimer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
